<template>
  <div>
    <el-table :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))" border
              style="width: 100%">
      <el-table-column prop="id" label="id" width="180"></el-table-column>
      <el-table-column prop="name" label="姓名" width="180"></el-table-column>
      <el-table-column prop="sex" label="性别" width="180"></el-table-column>
      <el-table-column prop="birthday" label="生日" width="180"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column align="left">
        <template slot="header" slot-scope="scope">
          <el-input v-model="search" size="mini" placeholder="输入姓名关键字搜索" prefix-icon="el-icon-search"/>
        </template>
        <template slot-scope="scope">
          <i class="el-icon-edit icon-size-margin" @click="handleEdit(scope.$index, scope.row)" ></i>
          <i class="el-icon-delete icon-size-margin"  @click="handleDelete(scope.$index, scope.row)"></i>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: "List",
  data() {
    return {
      tableData: [{
        id: '',
        birthday: '',
        name: '',
        address: '',
        sex: '',
      },],
      search: '',
    }
  },
  methods: {
    handleEdit(index, row) {//携带当前用户信息，以post方式，跳转到编辑页面
       //跳转路由的时候，需要用到配置路由中的name，使用路径则无法跳转！
       this.$router.push({name:"UserEdit",params:{id:row.id,birthday:row.birthday,name:row.name,address:row.address,sex:row.sex}});
    },
    loadPageDate(){
      this.$http.get("http://localhost:8081/user/findAll").then(res=>{
        this.tableData=res.data.results;
      });
    },
    handleDelete(index, row) {

      this.$confirm('此操作将永久删除用户信息, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {//执行删除
        let user={id:row.id};
        this.$http.post("http://localhost:8081/user/delete",user).then(res=>{
          this.loadPageDate();
          this.$message({
            message: res.data.msg,
            type: 'warning'
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  },
  created() {
    this.loadPageDate();
  },
  // 监听,当路由发生变化的时候执行
  watch:{
    $route:{
      handler(val,oldval){
        // console.log(val.path);
        if (val.path==='/users'){
          this.$http.get("http://localhost:8081/user/findAll").then(res=>{
            this.tableData=res.data.results;
          });
        }
      },
      // 深度观察监听
      deep: true
    }
  }
}
</script>

<style>
.icon-size-margin{
  font-size: 20px;
  margin-left: 10px;
  margin-right: 10px;
}
.icon-right{
  text-align: right;
}
</style>
